using System;
using System.Collections.Generic;
using WB.Mvc.Forms.Widgets;

namespace WB.Mvc.Forms
{
	/// <summary>
	/// A field for true or false input.
	/// </summary>
	public class BooleanField : Field
	{
		private bool val;

		/// <summary>
		/// Creates an instance of <see cref="BooleanField"/>.
		/// </summary>
		public BooleanField(string name) : base(name)
		{
		}

		/// <summary>
		/// Gets the widget used to render the input for this field.
		/// </summary>
		public override Widget GetWidget()
		{
			return new CheckBox(Name, new Dictionary<string, object> { { "checked", CoerceValue(Value) } });
		}

		/// <summary>
		/// Returns a boolean value indicating whether this field is <c>true</c> or <c>false</c>.
		/// Defaults to <c>false</c>.
		/// </summary>
		public override string Value
		{
			get { return val.ToString(); }
			set { val = CoerceValue(value); }
		}

		/// <summary>
		/// Validate the input of this <see cref="BooleanField"/>.
		/// </summary>
		public override void Validate()
		{
			// Intentionally empty.
		}

		/// <summary>
		/// Checks if <see cref="BooleanField.Value"/> is valid.
		/// </summary>
		public override bool IsValid
		{
			get { return true; }
		}

		private static bool CoerceValue(object value)
		{
			if (value == null)
				return false;
			if (value.ToString() == string.Empty)
				return false;

			if (value.ToString().Equals("false", StringComparison.InvariantCultureIgnoreCase))
				return false;
			if (value.ToString().Equals("true", StringComparison.InvariantCultureIgnoreCase))
				return true;
			return (value.ToString().Equals("0") || value.ToString().Equals("1"));
		}
	}
}